package com.simon.hse.activity.contractor;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.MyApplication;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.TrainPersonOutput;
import com.simon.hse.http.entity.TrainRecordInput;
import com.simon.hse.http.entity.TrainRecordOutput;
import com.simon.hse.interfaces.PopListener;
import com.simon.hse.utils.PopupWindowUtils;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * 培训记录
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_train_record)
public class TrainRecordActivity extends BaseActivity implements PopListener {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.iv_common_right)
    ImageView mIv_common_right;

    @ViewInject(R.id.ll_search_first)
    LinearLayout mLl_search_first;

    @ViewInject(R.id.ll_search_second)
    LinearLayout mLl_search_second;

    @ViewInject(R.id.tv_search_first)
    TextView mTv_search_first;

    @ViewInject(R.id.tv_search_second)
    TextView mTv_search_second;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;

    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private List<TrainRecordOutput.DataBean.PageDataBean> mDataBeanList = new ArrayList<>();// 培训记录
    private List<TrainPersonOutput.DataBean.PageDataBean> mListTrainPerson = new ArrayList<>();// 培训人
    private List<String> mListCourse = new ArrayList<>();// 培训记录
    private Boolean isFirst = true;// 第一次获取课件名称和培训人数据
    private String trainingCoursewareName;// 培训课名称
    private String contractorId;// 承包商ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mTv_common_title.setText("培训记录");
        mIv_common_right.setImageResource(R.mipmap.tab_add_icon);

        initRecyclerView();
        initTrainPerson();
        initData();
    }

    @Event(value = {R.id.iv_common_left, R.id.iv_common_right, R.id.ll_search_first, R.id.ll_search_second})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.iv_common_right:
                startActivityForResult(new Intent(TrainRecordActivity.this, AddTrainRecordActivity.class), 1);
                break;
            case R.id.ll_search_first:
                initTrainRecordPop();
                break;
            case R.id.ll_search_second:
                initTrainPersonPop();
                break;
        }
    }

    private void initRecyclerView() {
        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage*10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(TrainRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(TrainRecordActivity.this, R.layout.layout_item_train_record, mDataBeanList);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<TrainRecordOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, TrainRecordOutput.DataBean.PageDataBean dataBean) {
                TextView tv_record_condition_title = holder.getView(R.id.tv_record_condition_title);
                TextView tv_record_condition_person = holder.getView(R.id.tv_record_condition_person);
                TextView tv_record_condition_time = holder.getView(R.id.tv_record_condition_time);
                TextView tv_record_condition_first = holder.getView(R.id.tv_record_condition_first);
                TextView tv_record_condition_second = holder.getView(R.id.tv_record_condition_second);
                TextView tv_record_condition_third = holder.getView(R.id.tv_record_condition_third);

                tv_record_condition_title.setText(dataBean.getTrainingCoursewareName());
                String trainerText = dataBean.getTrainerText();
                if (TextUtils.isEmpty(trainerText)) {
                    trainerText = "    ";
                }
                tv_record_condition_person.setText(trainerText);
                String trainingDate = dataBean.getTrainingDate();
                if (trainingDate.contains(" ")) {
                    String[] split = trainingDate.split(" ");
                    trainingDate = split[0];
                }
                tv_record_condition_time.setText(trainingDate);
                tv_record_condition_first.setText("培训人：" + dataBean.getTrainerText());
                List<String> recordUser = dataBean.getCbS_TrainRecordUser();
                StringBuffer sb = new StringBuffer();
                for (String s : recordUser) {
                    sb.append(s + "、");
                }
                tv_record_condition_second.setText("参与人：" + sb.toString());
                tv_record_condition_third.setText("备注信息：" + dataBean.getRemarks());
            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                Intent intent = new Intent(TrainRecordActivity.this, AddTrainRecordActivity.class);
                Bundle bundle = new Bundle();
                TrainRecordOutput.DataBean.PageDataBean pageDataBean = mDataBeanList.get(position);
                bundle.putSerializable("RECORD_DATA", pageDataBean);
                bundle.putString("ID", pageDataBean.getId());
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    /**
     * 培训人
     */
    private void initTrainPerson() {
        TrainPersonOutput.DataBean.PageDataBean pageDataBean = new TrainPersonOutput.DataBean.PageDataBean();
        pageDataBean.setName("全部");
        pageDataBean.setId("");
        mListTrainPerson.add(pageDataBean);
        mListTrainPerson.addAll(MyApplication.getInstance().mListTrainPerson);
    }

    private void initData() {
        TrainRecordInput trainRecordInput = new TrainRecordInput();
        TrainRecordInput.ModelBean modelBean = new TrainRecordInput.ModelBean();
        TrainRecordInput.ModelBean.TrainerModelBean trainerModelBean = new TrainRecordInput.ModelBean.TrainerModelBean();
        if (!TextUtils.isEmpty(contractorId)) {
            trainerModelBean.setSysUserID(contractorId);
        }
        TrainRecordInput.ModelBean.CBSCourseBean cbsCourseBean = new TrainRecordInput.ModelBean.CBSCourseBean();
        if (!TextUtils.isEmpty(trainingCoursewareName)) {
            cbsCourseBean.setTrainingCoursewareName(trainingCoursewareName);
        }
        modelBean.setCBS_Course(cbsCourseBean);
        modelBean.setTrainerModel(trainerModelBean);
        trainRecordInput.setModel(modelBean);
        trainRecordInput.setLimit(10);
        trainRecordInput.setOffset(10 * (currentPage - 1));

        Call<String> call = HttpManager.getInstance().requestService().CONTRACTOR_TRAIN_RECORD(HttpManager.getInstance().requestBody(trainRecordInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                TrainRecordOutput trainRecordOutput = new Gson().fromJson(result, TrainRecordOutput.class);
                if (trainRecordOutput.getResult().equals("Success")) {
                    totalPage = trainRecordOutput.getData().getRowCount();
                    List<TrainRecordOutput.DataBean.PageDataBean> dataBeanList = trainRecordOutput.getData().getPageData();
                    mDataBeanList.addAll(dataBeanList);
                    if (isFirst) {
                        mListCourse.add("全部");
                        for (TrainRecordOutput.DataBean.PageDataBean pageDataBean : mDataBeanList) {
                            mListCourse.add(pageDataBean.getTrainingCoursewareName());
                        }
                        isFirst = false;
                    }
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(trainRecordOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 培训课件名称
     */
    private void initTrainRecordPop() {
        View inflate = LayoutInflater.from(TrainRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(TrainRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(TrainRecordActivity.this, R.layout.layout_item_common_more_department, mListCourse);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<String>() {
            @Override
            public void setItemData(CommonViewHolder holder, String dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean);
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                trainingCoursewareName = mListCourse.get(position);
                mTv_search_first.setText(trainingCoursewareName);
                if (position == 0) {
                    trainingCoursewareName = "";
                }
                mDataBeanList.clear();
                initData();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(TrainRecordActivity.this, inflate, mLl_search_first);
    }

    /**
     * 培训人
     */
    private void initTrainPersonPop() {
        View inflate = LayoutInflater.from(TrainRecordActivity.this).inflate(R.layout.layout_common_more_department, null);
        RecyclerView mRecyclerView = (RecyclerView) inflate.findViewById(R.id.common_recyclerview);
        LinearLayoutManager llm = new LinearLayoutManager(TrainRecordActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        CommonEmptyAdapter mCommonEmptyAdapter = new CommonEmptyAdapter(TrainRecordActivity.this, R.layout.layout_item_common_more_department, mListTrainPerson);
        mCommonEmptyAdapter.setItemDataListener(new CommonEmptyAdapter.ItemDataListener<TrainPersonOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemData(CommonViewHolder holder, TrainPersonOutput.DataBean.PageDataBean dataBean) {
                TextView tv_department = holder.getView(R.id.tv_department);
                tv_department.setText(dataBean.getName());
            }
        });

        mCommonEmptyAdapter.setOnItemClickListener(new CommonEmptyAdapter.OnItemClickListener() {
            @Override
            public void setOnItemClickListener(View view, int position) {
                TrainPersonOutput.DataBean.PageDataBean pageDataBean = mListTrainPerson.get(position);
                contractorId = pageDataBean.getId();
                mTv_search_second.setText(pageDataBean.getName());
                mDataBeanList.clear();
                initData();
                PopupWindowUtils.getInstance().closePop();
                upData();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mRecyclerView.setAdapter(mCommonEmptyAdapter);
        PopupWindowUtils.getInstance().createScalePopupWindow(TrainRecordActivity.this, inflate, mLl_search_second);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            if (bundle == null)
                return;
            if (requestCode == 1) {
                currentPage = 1;
                mDataBeanList.clear();
                initData();
            }
        }
    }

    @Override
    public void upData() {
        currentPage = 1;
        mDataBeanList.clear();
        initData();
    }
}
